/*
 * @Author: xiaosihan 
 * @Date: 2023-07-20 22:40:18 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2023-08-20 15:07:44
 */

import { fabric } from "fabric";
import { debounce } from "lodash";
import FabricCanvas from "./FabricCanvas";
import PrintArea from "./PrintArea";

//  商品组件组件打印编辑器
class ComponentPrintEditor {

  constructor() {
    window.componentPrintEditor = this;
  }

  //div容器元素
  divDom = (() => {
    const divDom = document.createElement("div");
    divDom.style.width = "512px";
    divDom.style.height = "512px";
    return divDom;
  })();

  // 画布
  canvas = (() => {
    const canvas = document.createElement('canvas');
    canvas.width = 512;
    canvas.height = 512;
    this.divDom.append(canvas);
    return canvas;
  })();

  fabricCanvas = (() => {
    const fabricCanvas = new FabricCanvas(this.canvas);
    fabricCanvas.selection = false;
    return fabricCanvas;
  })();

  setContainer(div: HTMLDivElement | null) {
    if (div) {
      div.style.overflow = "hidden";
      div.innerHTML = "";
      div.append(this.divDom);
    }
  }

  // 打印区域元素
  printArea = (() => {
    const printArea = new PrintArea();
    printArea.selectable = false;
    this.fabricCanvas.add(printArea);
    return printArea;
  })();

  // 部位的uv参考图
  uv = (() => {
    const uv = new fabric.Image("");
    this.fabricCanvas.add(uv);
    uv.selectable = false;
    return uv;
  })();

  // 设置uv图
  setUv(uvUrl?: string) {
    if (uvUrl) {
      this.uv.setSrc(uvUrl, () => {
        const scale = 512 / Math.max(this.uv.width || 1, this.uv.height || 1);
        this.uv.set({
          originX: "center",
          originY: "center",
          scaleX: scale,
          scaleY: scale,
          left: 512 * 0.5,
          top: 512 * 0.5,
          visible: true,
        });

        //设置裁剪区域的边长
        const { width = 500, height = 500 } = this.uv;
        this.printArea.set({
          sideLength: Math.max(width, height) * (1 / 2.8346)
        });

        this.render();
      }, { crossOrigin: "anonymous" });
    } else {
      this.uv.visible = false;
      this.render();
    }
    return this.uv;
  }

  // 设置打印区间
  setPrintArea(rect: Partial<{
    width: number, height: number, left: number, top: number,
    clip_width: number, clip_height: number, clip_left: number, clip_top: number,
    sideLength: number // 边长单位mm
  }> = {}) {
    this.printArea.set(rect);
    this.render();
  }

  // 渲染画布
  render() {
    this.fabricCanvas.requestRenderAll();
  }

}

const componentPrintEditor = new ComponentPrintEditor();

export default componentPrintEditor;
